package com.coolingme.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * 数据库连接池
 *
 * @author wangyue
 * @date 2020-09-16 23:26
 */
public class ConnectionPool {

    /**
     * 连接池
     */
    private Vector<Connection> pool;

    private String driveClassName = "org.postgresql.Driver";

    private String url = "jdbc:postgresql://127.0.0.1:5433/focus_groups?useAffectedRows=true&stringtype=unspecified";

    private String username = "postgres";

    private String password = "123456";

    private int poolSize = 3;

    public ConnectionPool() {
        pool = new Vector<>(poolSize);
        try {
            Class.forName(driveClassName);
            for (int i = 0; i < poolSize; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                pool.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 重置连接池
     *
     * @param newPoolSize 连接池的新的大小
     * @author wangyue
     * @date 2022/7/28 17:31
     */
    public void resetPool(Integer newPoolSize) {
        pool.clear();
        pool = new Vector<>(newPoolSize);
        try {
            Class.forName(driveClassName);
            for (int i = 0; i < newPoolSize; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                pool.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接并从池中去掉当前连接
     *
     * @return Connection
     */
    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        }
        return null;
    }

    /**
     * 释放连接，将连接对象放回池中
     *
     * @param conn Connection
     */
    public synchronized void release(Connection conn) {
        pool.add(conn);
    }

}
